import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';
import { environment } from '@env/environment';

@Component({
  selector: 'app-dashboard-c',
  templateUrl: './dashboard-c.component.html',
  styleUrls: ['./dashboard-c.component.scss'],
})
export class DashboardCComponent implements OnInit, OnDestroy {
  private inEventSource: EventSource;
  private outEventSource: EventSource;

  public record = {
    'in-user': {},
    'out-user': {},
  };

  private get inRecord() {
    return this.record['in-user'];
  }

  private get outRecord() {
    return this.record['out-user'];
  }

  public today = new Date();

  constructor(private zone: NgZone) {}

  ngOnInit() {
    this.initRecord();
    this.createEventSource();
  }

  initRecord() {
    ['警察', '职工', '外来人员'].forEach(key => {
      this.inRecord[key] = null;
      this.outRecord[key] = null;
    });
  }

  createEventSource() {
    this.inEventSource = new EventSource(environment.inEventSource);
    this.outEventSource = new EventSource(environment.outEventSource);
    this.inEventSource.onmessage = this.onMessage(this.inRecord);
    this.outEventSource.onmessage = this.onMessage(this.outRecord);
  }

  onMessage(record) {
    return event => {
      console.log(event);
      const { source }: { source: any } = JSON.parse(event.data);
      this.zone.run(() => {
        record[source.type] = source;
        this.record = { ...this.record };
      });

      console.log(record);
    };
  }

  ngOnDestroy() {
    this.inEventSource.close();
    this.outEventSource.close();
  }
}
